<?php
//this program will run every hour
set_time_limit(60*30);

	require_once "config.php";
	require_once dirname(__FILE__). '/util/connection.class.php';
	$dbconn = Connection::getInstance();
	
	$sql = 'select id from sites';
	$sites = $dbconn->query($sql);
	if(!empty($sites)){
		foreach ($sites as $site){
			$latestActivities = getLatestActivities($site['id'], $dbconn);
			if(null !== $latestActivities)
				clearData($site['id'], $latestActivities, $dbconn);
		}
	}
	
	function getLatestActivities($site_id, Connection $con){
		$ids = array();
		$sql = "select id from activities where site=? order by time desc limit 0, 5";
		$activities = $con->query($sql, array($site_id));
		if($activities){
			foreach ($activities as $activity)
				$ids[] = $activity['id'];
			return implode(' ,', $ids);
		}
		return null;
	}
	
	function clearData($site_id, $latestActivities, Connection $con){
		$sql = 'delete from activities where site=? and id not in (' . $latestActivities . ')';
		$con->execute($sql, array($site_id));
	}
	
?>